package ipt.dao.f4;

import ipt.util.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class Consola {

	
	public static void consolaConsulta(){
		
		Connection conn = null;
		PreparedStatement ptmt = null;
		ResultSet rs = null;
		
		try {
			conn = AlumnoJDBCDAO.getConnection();
			
			String consulta = Util.leerString();
			ptmt = conn.prepareStatement(consulta);
			rs=ptmt.executeQuery();
			ResultSetMetaData rSMD = rs.getMetaData();
			int numeroCampos = rSMD.getColumnCount();
			String texto = "";
			while (rs.next()) {
				for (int i = 1; i <= numeroCampos; ++i) {
					if (i < numeroCampos)
						texto += rs.getString(i) + " ";
					else
						texto += rs.getString(i).trim();
				}
				texto += "\n";
			}
			System.out.println(texto);
			ptmt.close();
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		} finally{
			try {
				if (ptmt != null)
					ptmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println("\n--- SQLException caught ---\n");
				while (e != null) {
					System.out.println("Message: " + e.getMessage() + "\n");
					System.out.println("SQLState: " + e.getSQLState() + "\n");
					System.out.println("ErrorCode: " + e.getErrorCode() + "\n");
					e = e.getNextException();
					System.out.println("");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
	
	public static void consolaUpdate(){
		Connection conn = null;
		PreparedStatement ptmt = null;
		
		try {
			conn = AlumnoJDBCDAO.getConnection();
			
			String consulta = Util.leerString();
			ptmt = conn.prepareStatement(consulta);
			ptmt.executeUpdate();
			ptmt.close();
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
	}
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int op;
		do{
			System.out.println("Seleccione una opcion\n1:Manipular BBDD \t2: Consultar BBDD\n3:Salir");
			op = Util.leerInt();
			if (op==1){
				System.out.println("Introduzca la query:");
				consolaUpdate();
			}else if(op==2){
				System.out.println("Introduzca la query:");
				consolaConsulta();
			}
		}while (op!=3);
		
	}

}
